// src/services/enum.service.ts
import { AppDataSource } from '@/config/AppDataSource';

class EnumService {
    private dataSource = AppDataSource;

    constructor() { }

    /**
     * 获取表数据并转换为枚举格式
     * @param tableNames 需要查询的表名数组
     * @returns 返回格式: { [tableName]: { value: id, name: name }[] }
     */
    async getTableEnums(reqData: Record<string, Record<string, any>>): Promise<Record<string, Array<{ value: string; name: string }>>> {
        const tableNames = Object.keys(reqData)
        // 验证表名是否合法
        await this.validateTables(tableNames);

        // 并行查询所有表
        const results = await Promise.all(
            tableNames.map(tableName =>
                this.queryTableToEnum(tableName)
            )
        )
        // 组装结果
        return tableNames.reduce((acc, tableName, index) => {
            acc[tableName] = results[index];
            return acc;
        }, {} as Record<string, any>);
    }

    /**
     * 查询单个表并转换为枚举格式
     */
    private async queryTableToEnum(tableName: string): Promise<Array<{ value: string; name: string }>> {

        const results: any = await this.dataSource
            .createQueryBuilder()
            .select(['id AS value', 'name'])
            .from(tableName, 't')
            .getRawMany();
        return results;

    }

    /**
     * 验证表名是否存在于数据库中
     */
    private async validateTables(tableNames: string[]): Promise<void> {

        const existingTables = await this.dataSource
            .createQueryBuilder()
            .select('table_name')
            .from('information_schema.tables', 'tables')
            .where('tables.table_schema = DATABASE()')
            .getRawMany();
        const existingTableNames = existingTables.map((t: any) => t.TABLE_NAME);
        for (const tableName of tableNames) {
            if (!existingTableNames.includes(tableName)) {
                throw new Error(`表 ${tableName} 不存在`);
            }
        }
        // await queryRunner.release();
    }
}

export default new EnumService()